package cn.codecang.mall.common.response;

import cn.codecang.mall.common.consts.ErrorCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

/**
 * Result 统一返回结果
 *
 * @author xiaoluo
 * @date 2023/6/2 16:41
 */
@Data
@AllArgsConstructor
public class Result<T> {
    /**
     * 操作成功
     */
    public static final Integer SUCCESS = 0;


    /**
     * 消息码
     */
    private Integer code;
    /**
     * 消息描述
     */
    private String msg;
    /**
     * 返回数据
     */
    private T data;

    public Result() {
        this.code = SUCCESS;
        this.msg = "操作成功";
        this.data = null;
    }

    public Result(T data) {
        this.code = SUCCESS;
        this.msg = "操作成功";
        this.data = data;
    }

    @Contract(value = " -> new", pure = true)
    public static <T> @NotNull Result<T> success() {
        return new Result<>();
    }

    @Contract(value = "_ -> new", pure = true)
    public static <T> @NotNull Result<T> success(T data) {
        return new Result<>(data);
    }

    @Contract("_ -> new")
    public static <T> @NotNull Result<T> error(@NotNull ErrorCode code) {
        return new Result<>(code.getCode(), code.getMsg(), null);
    }

    @Contract("_, _ -> new")
    public static <T> @NotNull Result<T> build(Integer code, String msg) {
        return new Result<>(code, msg, null);
    }

    @Contract("_, _, _ -> new")
    public static <T> @NotNull Result<T> build(Integer code, String msg, T data) {
        return new Result<>(code, msg, data);
    }
}
